package com.cloudcc.mobile.network;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.ImageInfo;
import com.cloudcc.mobile.entity.ManyImage;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostDMany;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostF;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostL;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostMessage;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostV;
import com.cloudcc.mobile.entity.chat.DraftBox;
import com.cloudcc.mobile.entity.comment.AddMicroComment;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.AddMicroPostMessageParser;
import com.cloudcc.mobile.parser.ImageParser;
import com.cloudcc.mobile.parser.ReturnCodeParser;
import com.cloudcc.mobile.service.AddMicroPostService;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UploadImgManyClient;
import com.cloudcc.mobile.util.UrlTools;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;

/**
 * 后台发送微贴
 * @author Administrator
 *
 */
public class AddMicroPostUtil {
	private Context context;
	private int num;
	AddMicroPostService service;
	AddMicroPostF addMicroPostF;
	AddMicroPostL addMicroPostL;
	AddMicroPostV addMicroPostV;//投票
	AddMicroPostDMany addMicroPostDMany;//多图
	AddMicroComment addMicroComment;
	List<AddImageInfo> list;
	private List<String> pzlist;
	private int a=0;
	private int b=0;
	private String aa=null;
	public AddMicroPostUtil(Context context,int num){
		this.context=context;
		this.num=num;
		pzlist=new ArrayList<String>();
		service=new AddMicroPostService();
	}
	/**	 * 普通的微贴	 */
	public void sendWeiTief(AddMicroPostF addMicroPostF,boolean isNotification){
		AppContext.ADDMICROPOST="addMicroPostF";
		if(isNotification){
			NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...", num);
		}
		this.addMicroPostF=addMicroPostF;
		String data=Json.toJson(addMicroPostF);
		Tools.i("qiandaowork", data);
		new MyTaskWF().execute(data);
	}
	/**	 * 链接的微贴	 */
	public void sendWeiTiel(AddMicroPostL addMicroPostL){
		AppContext.ADDMICROPOST="addMicroPostL";
		NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...", num);
		this.addMicroPostL=addMicroPostL;
		String data=Json.toJson(addMicroPostL);
		new MyTaskWF().execute(data);
	}
	/**	 * 投票的微贴	 */
	public void sendWeiTieV(AddMicroPostV addMicroPostV){
		AppContext.ADDMICROPOST="addMicroPostV";
		NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...", num);
		this.addMicroPostV=addMicroPostV;
		String data=Json.toJson(addMicroPostV);
		Tools.i("sendWeiTief", data);
		new MyTaskWF().execute(data);
	}
	/**	 * 多张图片的微贴	 */
	public void sendWeiTie(AddMicroPostDMany addMicroPostDMany,List<AddImageInfo> list,boolean isNotification){
		Tools.i("duozhangtupian", "--3-----sendWeiTie--------");
		this.list=list;
		AppContext.ADDMICROPOST="addMicroPostDMany";
		if(isNotification){
			NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...", num);
		}
		this.addMicroPostDMany=addMicroPostDMany;
		send();
	}
	private void send() {
		Tools.i("duozhangtupian", "--4-----进入send--------");
		for (int i = 0; i < list.size(); i++) {
			File file=new File(list.get(i).getImagePath());
			if(!file.exists()){
				list.remove(i);
			}
		}
		final String[] imagepaths=new String[list.size()];
		final List<ManyImage> imglist= new ArrayList<ManyImage>();
		for (int i = 0; i < list.size(); i++) {
			imagepaths[i]=list.get(i).getImagePath();
			ManyImage image=new ManyImage();
			image.setImgName(list.get(i).getImagePath());
			image.setAddress("");
			image.setImgHeight("");
			image.setImgWidth("");
			image.setImgId("");
			image.setImgType("jpg");
			imglist.add(image);
		}

		if(list.size()>0){//有图
			Tools.i("duozhangtupian", "--5-----进入list.size>0--------");
			ManyImage images=new ManyImage();
			images.setImgName(Tools.getTimeName(System.currentTimeMillis()));
			images.setAddress("");
			images.setImgHeight("");
			images.setImgWidth("");
			images.setImgId("");
			images.setImgType("png");
//			final String data=Json.toJson(images);
			final String data=Json.toJson(imglist);
			new Thread(){public void run() {
				try {
					String result=null;
					String Data = URLDecoder.decode(data, "UTF-8");
					final String url=UrlTools.url+UrlTools.imgupload_path+Data+"&binding="+AppContext.binding;
//					result=UploadClient.sendMany(imagepaths, url);
					result=UploadImgManyClient.sendMany(imagepaths, url);
//					result=UploadClient.sendMany(, actionUrl);
					if(result.equals("null")||result==null){
						handler.sendEmptyMessage(-3);
					}else{
						Message msg=handler.obtainMessage(1);
						msg.obj=result;
						msg.sendToTarget();
					}
//					
				} catch (Exception e) {
					Tools.handle(e);
				}

			}}.start();
		}else{
			handler.sendEmptyMessage(2);
		}
	}
	
	Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Tools.i("duozhangtupian", "--10-- case 1----");
				String result=(String) msg.obj;
				if(Tools.isNull(result)){
					NotificationUtils.clearNotification(context, num);
					SaveWTCaoGao();
					Tools.showInfo(context, "网络超时，微贴发表失败,已保存在草稿箱");
					return;
				}
				ImageInfo info=ImageParser.getImageInfo(result);
				boolean isresult=info.isResult();
				if(isresult){
					try {
						String images=info.getImgId();
						StringBuilder sb = new StringBuilder();
						JSONArray array=new JSONArray(images);
						for(int i=0;i<array.length();i++){
							sb.append(array.get(i)+",");
						}
						String a=sb.toString();
						addMicroPostDMany.setFileIds(a.substring(0, a.length()-1));
						String data=Json.toJson(addMicroPostDMany);
						Tools.i("duozhangtupian", "--10-- data----"+data);
						new MyTaskWF().execute(data);
					} catch (Exception e) {
						Tools.handle(e);
					}
				}else{
					NotificationUtils.clearNotification(context, num);
					SaveWTCaoGao();
					Tools.showInfo(context, "微贴发表失败,已保存在草稿箱");
					return;
				}
				break;
			case 2:
				Tools.showInfo(context, "请选择图片");
				break;
			case -3:
				NotificationUtils.clearNotification(context, num);
				SaveWTCaoGao();
				Tools.showInfo(context, "微贴发表失败！已保存草稿箱");
				break;
			}
			super.handleMessage(msg);
		}
	};
	/**  联网发送"微贴"*/
	class MyTaskWF extends AsyncTask<String, Void, String>{
		@Override
		protected String doInBackground(String... params) {
			String data=params[0];
			String json=null;
			List<NameValuePair> pairs=new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair("serviceName", AppContext.ADDMICROPOST));
			pairs.add(new BasicNameValuePair("data", data));
			pairs.add(new BasicNameValuePair("binding", AppContext.binding));
			String url=UrlTools.url+UrlTools.url_path;
			json=NetWork.post(url, pairs);
			Tools.i("duozhangtupian", "--11-- json----"+json);
			return json;
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			try {
				if(result==null||result.equals("NetworkError")){
					SaveWTCaoGao();
					Tools.showInfo(context, "网络异常,微贴发表失败,已保存在草稿箱");
					NotificationUtils.clearNotification(context, num);
					return ;
				}
				if(result.equals("outTime")){
					SaveWTCaoGao();
					Tools.showInfo(context, "网络超时，微贴发表失败,已保存在草稿箱");
					NotificationUtils.clearNotification(context, num);
					return;
				}
				String code=ReturnCodeParser.getReturnCode(result);
				if(code.equals("-2")){
					try {
						SaveWTCaoGao();
					} catch (Exception e) {
						Tools.handle(e);
					}
					Tools.showInfo(context, "登陆超时,请重新登录");
					NotificationUtils.clearNotification(context, num);
					return;
				}
				AddMicroPostMessage msg=AddMicroPostMessageParser.addMicroPost(result);
				boolean flag=msg.isResult();
				if(flag){
					Intent intent=new Intent(AppContext.INDEXADAPTER_SHUAXIN);
					context.sendBroadcast(intent);
					Tools.showInfo(context, "微贴发表成功");
					NotificationUtils.clearNotification(context, num);
				}else{
					SaveWTCaoGao();
					Tools.showInfo(context, "微贴发表失败！已保存草稿箱");
					NotificationUtils.clearNotification(context, num);
				}
			} catch (Exception e) {
				Tools.handle(e);
			}
		}
	}

	/** 把失败的"微贴保存到草稿箱"*/
	private void SaveWTCaoGao() {
		try {
			Tools.i("sendWeiTief", "多张图片进入草稿箱");
			saveWTDraftBox();
		} catch (DbException e) {
			Tools.handle(e);
		}
		Intent caogao=new Intent(AppContext.CAOGAO_NUM);
		context.sendBroadcast(caogao);
	}

	/** 把失败的"微贴保存到数据库"*/
	private void saveWTDraftBox() throws DbException{
		Tools.i("sendWeiTief", "调用saveDraftBox()保存到数据库");
		DbUtils db=DbUtils.create(context,UserManager.getManager().getUser().userId+"box.db");
		DraftBox box=new DraftBox();
		box.setType("2");
		box.setTime(Tools.getTime(System.currentTimeMillis()));
		box.setIsNew("1");
		box.setClickable(true);
		if(AppContext.ADDMICROPOST.equals("addMicroPostF")){
			box.setLeixing("addMicroPostF");
			addMicroPostF.setParent(box);
			box.setAddMicroPostF(addMicroPostF);
			db.saveBindingId(addMicroPostF);
		}else if(AppContext.ADDMICROPOST.equals("addMicroPostL")){
			box.setLeixing("addMicroPostL");
			addMicroPostL.setParent(box);
			box.setAddMicroPostL(addMicroPostL);
			db.saveBindingId(addMicroPostL);
		}else if(AppContext.ADDMICROPOST.equals("addMicroPostDMany")){
			String pz="";
			if(list.size()>0){
				pz=list.get(0).getImagePath();
				for(int i=1;i<list.size();i++){
					pz=pz+","+list.get(i).getImagePath();
				}
			}
			addMicroPostDMany.setList(pz);//路径存在list里面
			box.setLeixing("addMicroPostDMany");
			addMicroPostDMany.setParent(box);
			box.setAddMicroPostDMany(addMicroPostDMany);
			db.saveBindingId(addMicroPostDMany);

		}else if(AppContext.ADDMICROPOST.equals("addMicroPostV")){
			Tools.i("sendWeiTief", "-----投票保存草稿箱存数据库-----");
			box.setLeixing("addMicroPostV");
			addMicroPostV.setParent(box);
			box.setAddMicroPostV(addMicroPostV);
			db.saveBindingId(addMicroPostV);
		}
	}
	
}
